// 全局变量
let currentVideos = [];
let currentPage = 1;
let isLoading = false;
let hasMore = true;
let currentFilters = {
    search: '',
    tag: '',
    series: '',
    sort: 'updated'
};

// DOM元素
const videoGrid = document.getElementById('videoGrid');
const searchInput = document.getElementById('searchInput');
const searchBtn = document.getElementById('searchBtn');
const tagFilter = document.getElementById('tagFilter');
const seriesFilter = document.getElementById('seriesFilter');
const sortFilter = document.getElementById('sortFilter');
const scanBtn = document.getElementById('scanBtn');
const refreshBtn = document.getElementById('refreshBtn');
const loadMoreBtn = document.getElementById('loadMoreBtn');
const loadMore = document.getElementById('loadMore');

// 模态框元素
const videoModal = document.getElementById('videoModal');
const editModal = document.getElementById('editModal');
const scanModal = document.getElementById('scanModal');
const videoPlayer = document.getElementById('videoPlayer');
const editForm = document.getElementById('editForm');

// 初始化应用
document.addEventListener('DOMContentLoaded', function () {
    initializeApp();
    setupEventListeners();
    loadVideos();
    loadFilters();
});

// 初始化应用
function initializeApp () {
    console.log('个人智能视频库系统初始化完成');
}

// 设置事件监听器
function setupEventListeners () {
    // 搜索功能
    searchBtn.addEventListener('click', handleSearch);
    searchInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') handleSearch();
    });

    // 筛选功能
    tagFilter.addEventListener('change', handleFilterChange);
    seriesFilter.addEventListener('change', handleFilterChange);
    sortFilter.addEventListener('change', handleFilterChange);

    // 操作按钮
    scanBtn.addEventListener('click', showScanModal);
    refreshBtn.addEventListener('click', refreshVideos);
    loadMoreBtn.addEventListener('click', loadMoreVideos);

    // 模态框关闭
    setupModalCloseListeners();

    // 表单提交
    editForm.addEventListener('submit', handleEditSubmit);

    // 扫描功能
    document.getElementById('startScan').addEventListener('click', startScan);
    document.getElementById('cancelScan').addEventListener('click', hideScanModal);
    document.getElementById('cancelEdit').addEventListener('click', () => hideModal(editModal));
    document.getElementById('browseBtn').addEventListener('click', handleBrowse);

    // 目录选择器事件
    document.getElementById('directoryPicker').addEventListener('change', handleDirectorySelection);
}

// 设置模态框关闭监听器
function setupModalCloseListeners () {
    // 视频播放模态框
    videoModal.querySelector('.close').addEventListener('click', () => hideModal(videoModal));
    videoModal.addEventListener('click', (e) => {
        if (e.target === videoModal) hideModal(videoModal);
    });

    // 编辑模态框
    editModal.querySelector('.close').addEventListener('click', () => hideModal(editModal));
    editModal.addEventListener('click', (e) => {
        if (e.target === editModal) hideModal(editModal);
    });

    // 扫描模态框
    scanModal.addEventListener('click', (e) => {
        if (e.target === scanModal) hideScanModal();
    });
}

// 加载视频列表
function loadVideos (reset = true) {
    if (isLoading) return;

    isLoading = true;

    if (reset) {
        currentPage = 1;
        currentVideos = [];
        videoGrid.innerHTML = '<div class="loading">正在加载视频...</div>';
    }

    const params = new URLSearchParams();
    if (currentFilters.search) params.append('search', currentFilters.search);
    if (currentFilters.tag) params.append('tag', currentFilters.tag);
    if (currentFilters.series) params.append('series', currentFilters.series);
    params.append('limit', '12');
    if (!reset) params.append('offset', (currentPage - 1) * 12);

    fetch(`/api/videos?${params}`)
        .then(response => response.json())
        .then(videos => {
            if (reset) {
                currentVideos = videos;
            } else {
                currentVideos = [...currentVideos, ...videos];
            }

            renderVideos();
            updateLoadMoreButton(videos.length === 12);

            isLoading = false;
        })
        .catch(error => {
            console.error('加载视频失败:', error);
            videoGrid.innerHTML = '<div class="loading">加载失败，请刷新页面</div>';
            isLoading = false;
        });
}

// 渲染视频网格
function renderVideos () {
    if (currentVideos.length === 0) {
        videoGrid.innerHTML = `
            <div class="empty-state">
                <h3>暂无视频</h3>
                <p>点击"扫描视频"按钮导入您的视频文件</p>
            </div>
        `;
        loadMore.style.display = 'none';
        return;
    }

    const videosHTML = currentVideos.map(video => createVideoCard(video)).join('');
    videoGrid.innerHTML = videosHTML;

    // 添加视频卡片点击事件
    document.querySelectorAll('.video-card').forEach((card, index) => {
        card.addEventListener('click', () => playVideo(currentVideos[index]));
    });
}

// 创建视频卡片HTML
function createVideoCard (video) {
    const fileSize = formatFileSize(video.filesize);
    const ratingStars = getRatingStars(video.rating);
    const tags = video.tags ? video.tags.split(',').slice(0, 3) : [];

    return `
        <div class="video-card" data-id="${video.id}">
            <div class="video-thumbnail"></div>
            <div class="video-info">
                <div class="video-title" title="${video.title}">${video.title}</div>
                <div class="video-meta">
                    <span class="file-size">${fileSize}</span>
                    <span class="rating-stars">${ratingStars}</span>
                </div>
                ${tags.length > 0 ? `
                    <div class="video-tags">
                        ${tags.map(tag => `<span class="tag">${tag.trim()}</span>`).join('')}
                    </div>
                ` : ''}
                <div class="video-actions">
                    <button class="action-btn" onclick="event.stopPropagation(); playVideo(${JSON.stringify(video).replace(/"/g, '"')})">
                        播放
                    </button>
                    <button class="action-btn" onclick="event.stopPropagation(); editVideo(${JSON.stringify(video).replace(/"/g, '"')})">
                        编辑
                    </button>
                </div>
            </div>
        </div>
    `;
}

// 处理搜索
function handleSearch () {
    currentFilters.search = searchInput.value.trim();
    currentPage = 1;
    loadVideos(true);
}

// 处理筛选变化
function handleFilterChange () {
    currentFilters.tag = tagFilter.value;
    currentFilters.series = seriesFilter.value;
    currentFilters.sort = sortFilter.value;
    currentPage = 1;
    loadVideos(true);
}

// 刷新视频列表
function refreshVideos () {
    loadVideos(true);
    loadFilters();
}

// 加载更多视频
function loadMoreVideos () {
    currentPage++;
    loadVideos(false);
}

// 更新加载更多按钮
function updateLoadMoreButton (show) {
    hasMore = show;
    loadMore.style.display = show ? 'block' : 'none';
}

// 加载筛选器选项
function loadFilters () {
    // 加载标签
    fetch('/api/tags')
        .then(response => response.json())
        .then(tags => {
            tagFilter.innerHTML = '<option value="">所有标签</option>';
            tags.forEach(tag => {
                tagFilter.innerHTML += `<option value="${tag}">${tag}</option>`;
            });
        });

    // 加载系列
    fetch('/api/series')
        .then(response => response.json())
        .then(series => {
            seriesFilter.innerHTML = '<option value="">所有系列</option>';
            series.forEach(s => {
                seriesFilter.innerHTML += `<option value="${s}">${s}</option>`;
            });
        });
}

// 播放视频
function playVideo (video) {
    const videoUrl = `/api/video/${encodeURIComponent(video.filename)}`;

    document.getElementById('modalTitle').textContent = video.title;
    document.getElementById('infoSize').textContent = formatFileSize(video.filesize);
    document.getElementById('infoViews').textContent = `${video.view_count} 次`;
    document.getElementById('infoRating').textContent = getRatingStars(video.rating);

    videoPlayer.src = videoUrl;
    showModal(videoModal);

    // 视频播放结束事件
    videoPlayer.onended = () => {
        // 可以在这里添加播放结束后的逻辑
    };
}

// 编辑视频
function editVideo (video) {
    document.getElementById('editId').value = video.id;
    document.getElementById('editTitle').value = video.title;
    document.getElementById('editAuthor').value = video.author || '';
    document.getElementById('editSeries').value = video.series || '';
    document.getElementById('editTags').value = video.tags || '';
    document.getElementById('editRating').value = video.rating || 0;
    document.getElementById('editDescription').value = video.description || '';

    showModal(editModal);
}

// 处理编辑表单提交
function handleEditSubmit (e) {
    e.preventDefault();

    const id = document.getElementById('editId').value;
    const updates = {
        title: document.getElementById('editTitle').value,
        author: document.getElementById('editAuthor').value,
        series: document.getElementById('editSeries').value,
        tags: document.getElementById('editTags').value,
        rating: parseInt(document.getElementById('editRating').value),
        description: document.getElementById('editDescription').value
    };

    fetch(`/api/videos/${id}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(updates)
    })
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                alert('更新成功！');
                hideModal(editModal);
                refreshVideos();
            } else {
                alert('更新失败: ' + result.error);
            }
        })
        .catch(error => {
            console.error('更新失败:', error);
            alert('更新失败，请重试');
        });
}

// 显示扫描模态框
function showScanModal () {
    document.getElementById('scanStatus').textContent = '准备开始扫描...';
    document.getElementById('progressFill').style.width = '0%';
    document.getElementById('startScan').style.display = 'block';
    document.getElementById('cancelScan').style.display = 'none';
    showModal(scanModal);
}

// 隐藏扫描模态框
function hideScanModal () {
    hideModal(scanModal);
}

// 处理浏览按钮点击
function handleBrowse () {
    const directoryPicker = document.getElementById('directoryPicker');

    // 检查浏览器是否支持目录选择
    if (directoryPicker.webkitdirectory !== undefined) {
        // 支持目录选择（Chrome/Edge）
        directoryPicker.click();
    } else {
        // 不支持目录选择，回退到手动输入
        const currentPath = document.getElementById('directoryInput').value;
        const directoryPath = prompt(
            '您的浏览器不支持目录选择功能\n\n' +
            '请输入视频目录的完整路径：\n\n' +
            '例如：\n' +
            'Windows: D:\\Videos 或 C:\\Users\\用户名\\Videos\n' +
            'Linux/Mac: /home/用户名/Videos 或 /Users/用户名/Videos\n\n' +
            '注意：请确保您有该目录的读取权限',
            currentPath || 'D:\\Videos'
        );

        if (directoryPath !== null && directoryPath.trim() !== '') {
            document.getElementById('directoryInput').value = directoryPath.trim();
        }
    }
}

// 处理目录选择结果
function handleDirectorySelection (event) {
    const files = event.target.files;
    if (files.length > 0) {
        // 在Web环境中无法获取绝对路径，只能获取相对路径
        // 显示提示信息，让用户手动输入绝对路径
        const firstFile = files[0];
        const relativePath = firstFile.webkitRelativePath || firstFile.name;
        const directoryPath = relativePath.substring(0, relativePath.lastIndexOf('/'));

        // 显示提示，让用户输入绝对路径
        const absolutePath = prompt(
            '已选择目录（相对路径）: ' + directoryPath + '\n\n' +
            '由于浏览器安全限制，无法自动获取目录的绝对路径。\n' +
            '请输入该目录的完整绝对路径：\n\n' +
            '例如：\n' +
            'Windows: D:\\Videos 或 C:\\Users\\用户名\\Videos\n' +
            'Linux/Mac: /home/用户名/Videos 或 /Users/用户名/Videos',
            document.getElementById('directoryInput').value || 'D:\\Videos'
        );

        if (absolutePath !== null && absolutePath.trim() !== '') {
            document.getElementById('directoryInput').value = absolutePath.trim();
        }

        // 重置文件选择器，以便可以再次选择
        event.target.value = '';
    }
}

// 开始扫描
function startScan () {
    const videoDir = document.getElementById('directoryInput').value.trim();

    if (!videoDir) {
        alert('请选择视频目录');
        return;
    }

    document.getElementById('startScan').style.display = 'none';
    document.getElementById('cancelScan').style.display = 'block';
    document.getElementById('scanStatus').textContent = '正在扫描视频文件...';
    document.getElementById('progressFill').style.width = '30%';

    fetch('/api/scan-videos', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            videoDir: videoDir
        })
    })
        .then(response => response.json())
        .then(result => {
            document.getElementById('progressFill').style.width = '100%';

            if (result.success) {
                document.getElementById('scanStatus').textContent =
                    `扫描完成！导入 ${result.imported} 个视频，跳过 ${result.skipped} 个重复视频`;

                setTimeout(() => {
                    hideScanModal();
                    refreshVideos();
                }, 2000);
            } else {
                document.getElementById('scanStatus').textContent = '扫描失败: ' + result.error;
            }
        })
        .catch(error => {
            console.error('扫描失败:', error);
            document.getElementById('scanStatus').textContent = '扫描失败，请重试';
        });
}

// 显示模态框
function showModal (modal) {
    modal.style.display = 'block';
    document.body.style.overflow = 'hidden';
}

// 隐藏模态框
function hideModal (modal) {
    modal.style.display = 'none';
    document.body.style.overflow = 'auto';

    // 停止视频播放
    if (modal === videoModal) {
        videoPlayer.pause();
        videoPlayer.src = '';
    }
}

// 工具函数

// 格式化文件大小
function formatFileSize (bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 获取评分星星
function getRatingStars (rating) {
    if (!rating || rating === 0) return '未评分';
    return '★'.repeat(rating) + '☆'.repeat(5 - rating);
}

// 防抖函数
function debounce (func, wait) {
    let timeout;
    return function executedFunction (...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 导出函数供全局使用
window.playVideo = playVideo;
window.editVideo = editVideo;
